import { login, logout, getInfo, changePsw } from '@/api/login'
import { getToken, removeToken } from '@/utils/auth'
import { getStudentInfoById } from '@/api/bussiness/member/student'
import { getTeacherInfoById } from '@/api/bussiness/member/teacher'
import { getAccountByUsername } from '@/api/bussiness/auth/account'

import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menus: undefined,
    role: '', // 角色code
    userType: '', // 用户类型,1学生，2教师
    memberInfo: null // 账户对应人员信息
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_MEMBER_INFO: (state, memberInfo) => {
    state.memberInfo = memberInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    commit('SET_TOKEN', '')
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        commit('SET_TOKEN', response.data.token)
        // setToken(response.data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const data = response.data
        commit('SET_NAME', data.nickName)
        commit('SET_AVATAR', 'http://git.oschina.net/uploads/42/547642_geek_qi.png?1499487420')
        commit('SET_ROLE', data.role)

        const menus = {}
        if (data.menus && JSON.stringify(data.menus) !== '[]') {
          for (let i = 0; i < data.menus.length; i++) {
            menus[data.menus[i].code] = true
          }
        }
        commit('SET_MENUS', menus)
        /* const elements = {}
        for (let i = 0; i < data.elements.length; i++) {
          elements[data.elements[i].code] = true
        }
        commit('SET_ELEMENTS', elements) */
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取人员信息
  getMemInfo({ commit, state }) {
    return new Promise((res, rej) => {
      if (state.memberInfo) {
        res({ memberInfo: state.memberInfo, userType: state.userType })
        return
      }
      getAccountByUsername().then(({ data }) => {
        const userType = data.roleType === 1 ? 1 : 2
        state.userType = userType
        if (userType === 1) {
          getStudentInfoById(data.userId).then(({ data }) => {
            // 保存用户人员信息
            commit('SET_MEMBER_INFO', data)
            res({ memberInfo: data, userType: userType })
          })
        } else if (userType === 2) {
          getTeacherInfoById(data.userId).then(({ data }) => {
            // 保存用户人员信息
            commit('SET_MEMBER_INFO', data)
            res({ memberInfo: data, userType: userType })
          })
        }
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then((res) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // 修改密码
  changePsw({ commit }, reqData) {
    return new Promise((resolve, reject) => {
      changePsw(reqData).then((res) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

